<template>
  <el-dialog v-model="visible" title="编辑" :close-on-click-modal="false" :fullscreen="true">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="属性设置" name="field">
        <vxe-table
            ref="fieldTable"
            border
            row-key
            class="sortable-row-gen"
            :data="fieldList"
            :checkbox-config="{ checkStrictly: true }"
            :edit-config="{ trigger: 'click', mode: 'cell' }"
        >
          <vxe-column type="seq" width="60"></vxe-column>
          <vxe-column width="60" title="拖动">
            <template #default>
							<span class="drag-btn">
								<i class="vxe-icon-sort"></i>
							</span>
            </template>
            <template #header>
              <el-tooltip class="item" effect="dark" content="按住后可以上下拖动排序" placement="top-start">
                <i class="vxe-icon-question-circle-fill"></i>
              </el-tooltip>
            </template>
          </vxe-column>
          <vxe-column field="fieldName" title="字段名"></vxe-column>
          <vxe-column field="fieldComment" title="说明" :edit-render="{ name: 'input' }"></vxe-column>
          <vxe-column field="fieldType" title="字段类型"></vxe-column>
          <vxe-column field="attrName" title="属性名" :edit-render="{ name: 'input' }"></vxe-column>
          <vxe-column field="attrType" title="属性类型">
            <template #default="{ row }">
              <vxe-select v-model="row.attrType">
                <vxe-option v-for="item in typeList" :key="item.value" :value="item.value"
                            :label="item.label"></vxe-option>
              </vxe-select>
            </template>
          </vxe-column>
          <vxe-column field="autoFill" title="自动填充">
            <template #default="{ row }">
              <vxe-select v-model="row.autoFill" clearable>
                <vxe-option v-for="item in fillList" :key="item.value" :value="item.value"
                            :label="item.label"></vxe-option>
              </vxe-select>
            </template>
          </vxe-column>
          <vxe-column field="primaryPk" title="主键">
            <template #default="{ row }">
              <vxe-checkbox v-model="row.primaryPk"></vxe-checkbox>
            </template>
          </vxe-column>
        </vxe-table>
      </el-tab-pane>
      <el-tab-pane label="表单页面" name="form">
        <vxe-table
            ref="formTable"
            border
            row-key
            :data="fieldList"
            :checkbox-config="{ checkStrictly: true }"
            :edit-config="{ trigger: 'click', mode: 'cell' }"
        >
          <vxe-column field="attrName" title="属性名"></vxe-column>
          <vxe-column field="fieldComment" title="说明"></vxe-column>
          <vxe-column field="formItem" title="表单显示">
            <template #default="{ row }">
              <vxe-checkbox v-model="row.formItem"></vxe-checkbox>
            </template>
          </vxe-column>
          <vxe-column field="formRequired" title="表单必填">
            <template #default="{ row }">
              <vxe-checkbox v-model="row.formRequired"></vxe-checkbox>
            </template>
          </vxe-column>
<!--          <vxe-column field="formValidator" title="表单效验" :edit-render="{ name: 'input' }"></vxe-column>-->
          <vxe-column field="formType" title="表单类型">
            <template #default="{ row }">
              <vxe-select v-model="row.formType">
                <vxe-option v-for="item in formTypeList" :key="item.value" :value="item.value"
                            :label="item.label"></vxe-option>
              </vxe-select>
            </template>
          </vxe-column>
          <vxe-column field="formDict" title="表单字典类型" :edit-render="{ name: 'input' }"></vxe-column>
        </vxe-table>
      </el-tab-pane>
      <el-tab-pane label="列表查询" name="third">
        <vxe-table
            ref="gridTable"
            border
            row-key
            :data="fieldList"
            :checkbox-config="{ checkStrictly: true }"
            :edit-config="{ trigger: 'click', mode: 'cell' }"
        >
          <vxe-column field="attrName" title="属性名"></vxe-column>
          <vxe-column field="fieldComment" title="说明"></vxe-column>
          <vxe-column field="gridItem" title="列表显示">
            <template #default="{ row }">
              <vxe-checkbox v-model="row.gridItem"></vxe-checkbox>
            </template>
          </vxe-column>
          <vxe-column field="queryItem" title="查询显示">
            <template #default="{ row }">
              <vxe-checkbox v-model="row.queryItem"></vxe-checkbox>
            </template>
          </vxe-column>
          <vxe-column field="queryType" title="查询方式">
            <template #default="{ row }">
              <vxe-select v-model="row.queryType">
                <vxe-option v-for="item in queryList" :key="item.value" :value="item.value"
                            :label="item.label"></vxe-option>
              </vxe-select>
            </template>
          </vxe-column>
          <vxe-column field="queryFormType" title="查询表单类型">
            <template #default="{ row }">
              <vxe-select v-model="row.queryFormType">
                <vxe-option v-for="item in formTypeList" :key="item.value" :value="item.value"
                            :label="item.label"></vxe-option>
              </vxe-select>
            </template>
          </vxe-column>
          <vxe-column field="queryDict" title="查询字典类型" :edit-render="{ name: 'input' }"></vxe-column>
        </vxe-table>
      </el-tab-pane>
      <el-tab-pane label="基本配置" name="generate">
        <el-form ref="dataFormRef" :model="dataForm" :rules="dataRules" label-width="120px">
          <el-row>
            <el-col :span="24">
              <el-form-item label="所属项目" prop="">
                  <el-select v-model="dataForm.sysProjectId" placeholder="所属项目" style="width: 100%" @change="projectChange" clearable>
                    <el-option v-for="item in projectList" :key="item.id" :label="item.projectName"
                               :value="item.id"></el-option>
                  </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="表名" prop="tableName">
                <el-input v-model="dataForm.tableName" disabled placeholder="表名"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="说明" prop="tableComment">
                <el-input v-model="dataForm.tableComment" placeholder="说明"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="类名" prop="className">
                <el-input v-model="dataForm.className" placeholder="类名"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="baseclassId" label="基类">
                <el-select v-model="dataForm.baseclassId" placeholder="基类" style="width: 100%" clearable>
                  <el-option v-for="item in baseClassList" :key="item.id" :label="item.code"
                             :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="模块名" prop="moduleName">
                <el-input v-model="dataForm.moduleName" placeholder="模块名"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="功能名" prop="functionName">
                <el-input v-model="dataForm.functionName" placeholder="功能名"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="项目包名" prop="packageName">
                <el-input v-model="dataForm.packageName" placeholder="项目包名"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="默认作者" prop="author">
                <el-input v-model="dataForm.author" placeholder="默认作者"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="生成方式" prop="generatorType">
                <el-radio-group v-model="dataForm.generatorType">
                  <el-radio :label="0">zip压缩包</el-radio>
                  <el-radio :label="1">自定义路径</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item v-if="dataForm.generatorType === 1" label="后端生成路径" prop="backendPath">
            <el-input v-model="dataForm.backendPath" placeholder="后端生成路径"></el-input>
          </el-form-item>
          <el-form-item v-if="dataForm.generatorType === 1" label="前端生成路径" prop="frontendPath">
            <el-input v-model="dataForm.frontendPath" placeholder="前端生成路径"></el-input>
          </el-form-item>
          <el-row>
            <el-col :span="24">关联信息<el-button type="primary" style="margin-left: 5px" size="small" :icon="Plus" circle @click="addSubTable()"/></el-col>
          </el-row>
          <el-divider />
          <el-row v-for="(val,index) in dataForm.subTableList">
            <el-col :span="8">
              <el-form-item label="关联主表字段" prop="mianTableFkName">
                <el-select v-model="val.mianTableFkName" placeholder="请选择关联主表字段" clearable  style="width: 100%">
                <el-option v-for="(item,index) in fieldList" :key="index" :value="item.fieldName" :label="item.fieldName"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="关联子表" prop="subTableId">
                <el-select v-model="val.subTableId" placeholder="请选择关联子表" clearable  style="width: 100%" @change="selectSubTable">
                  <el-option v-for="(item,index) in subsTableList" :key="index" :value="item.id" :label="item.tableName"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="关联子表字段" prop="subTableFkName">
                <el-select v-model="val.subTableFkName" placeholder="请选择关联子表字段" clearable  style="width: 100%">
                  <el-option v-for="(item,index) in subTableFieldList" :key="index" :value="item.fieldName" :label="item.fieldName"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-tab-pane>
    </el-tabs>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="submitHandle()">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { nextTick, reactive, ref } from "vue";
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, TabsPaneContext } from "element-plus/es";
import Sortable from "sortablejs";
import { useTableFieldSubmitApi, useTableSubmitApi,useTableListApi,useTableFieldListApi } from "@/api/table";
import { useTableApi } from "@/api/table";
import { useFieldTypeListApi } from "@/api/fieldType";
import { VxeTableInstance } from "vxe-table";
import { useBaseClassListApi } from "@/api/baseClass";
import { projectListApi } from "@/api/project";
import { projectConfigApi } from "@/api/projectConfig";

const activeName = ref();
const fieldTable = ref<VxeTableInstance>();
const formTable = ref<VxeTableInstance>();
const gridTable = ref<VxeTableInstance>();
const tableIndex = ref<any>();
const handleClick = (tab: TabsPaneContext) => {
  console.log(fieldList.value);
  if (tab.paneName !== "field") {
    formTable.value?.loadData(fieldList.value);
    gridTable.value?.loadData(fieldList.value);
  }
  tableIndex.value = tab.index;
};

const emit = defineEmits(["refreshDataList"]);
const visible = ref(false);
const dataFormRef = ref();

const sortable = ref() as any;

const typeList = ref([]) as any;
const tableId = ref();
const fieldList = ref([]);
const subsTableList = ref([]);
const subTableFieldList=ref([])
const fillList = reactive([
  { label: "DEFAULT", value: "DEFAULT" },
  { label: "INSERT", value: "INSERT" },
  { label: "UPDATE", value: "UPDATE" },
  { label: "INSERT_UPDATE", value: "INSERT_UPDATE" }
]);

const queryList = reactive([
  { label: "=", value: "=" },
  { label: "!=", value: "!=" },
  { label: ">", value: ">" },
  { label: ">=", value: ">=" },
  { label: "<", value: "<" },
  { label: "<=", value: "<=" },
  { label: "like", value: "like" },
  { label: "left like", value: "left like" },
  { label: "right like", value: "right like" }
]);

const formTypeList = reactive([
  { label: "单行文本", value: "text" },
  { label: "多行文本", value: "textarea" },
  { label: "富文本编辑器", value: "editor" },
  { label: "下拉框", value: "select" },
  { label: "单选按钮", value: "radio" },
  { label: "复选框", value: "checkbox" },
  { label: "日期", value: "date" },
  { label: "日期时间", value: "datetime" },
  { label: "图片上传", value: "image" },
]);

const baseClassList = ref<any[]>([]);
const projectList = ref<any[]>([]);
const dataForm = reactive({
  id: "",
  baseclassId: "",
  generatorType: 0,
  formLayout: 1,
  backendPath: "",
  frontendPath: "",
  packageName: "",
  email: "",
  author: "",
  version: "",
  moduleName: "",
  functionName: "",
  className: "",
  tableComment: "",
  tableName: "",
  subTableList:[]
});
const init = (id: number) => {
  visible.value = true;
  tableId.value = id;

  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }

  activeName.value = "field";

  rowDrop();
  getTable(id);
  getFieldTypeList();
  getBaseClassList();
  getSubTableList();
  getProjectList();
};

const rowDrop = () => {
  nextTick(() => {
    const el: any = window.document.querySelector(".body--wrapper>.vxe-table--body tbody");
    sortable.value = Sortable.create(el, {
      handle: ".drag-btn",
      onEnd: (e: any) => {
        const { newIndex, oldIndex } = e;
        const currRow = fieldList.value.splice(oldIndex, 1)[0];
        fieldList.value.splice(newIndex, 0, currRow);
      }
    });
  });
};

const getBaseClassList = () => {
  useBaseClassListApi().then(res => {
    baseClassList.value = res.data;
  });
};

const getProjectList = () => {
  projectListApi().then(res => {
    projectList.value = res.data;
  });
};

const getTable = (id: number) => {
  useTableApi(id).then(res => {
    fieldList.value = res.data.fieldList;
    Object.assign(dataForm, res.data);
  });
};

const getFieldTypeList = async () => {
  typeList.value = [];
  // 获取数据
  const { data } = await useFieldTypeListApi();
  // 设置属性类型值
  data.forEach((item: any) => typeList.value.push({ label: item, value: item }));
  // 增加Object类型
  typeList.value.push({ label: "Object", value: "Object" });
};

//获取所有导入的表
const getSubTableList =() =>{
  useTableListApi(null).then(res =>{
    subsTableList.value = res.data
  })
}

//获取表中所有字段
const getSubTableFieldList = (tableId:any) =>{
  useTableFieldListApi(tableId).then(res =>{
    subTableFieldList.value = res.data
  })
}

const selectSubTable = (val:any)=>{
  getSubTableFieldList(val)
}

const projectChange = (vale:any)=>{
  projectConfigApi(vale).then(res =>{
    dataForm.baseclassId = res.data.baseclassId
    dataForm.moduleName = res.data.moduleName
    dataForm.packageName = res.data.packageName
    dataForm.author = res.data.author
    dataForm.backendPath = res.data.backendPath
    dataForm.frontendPath = res.data.frontendPath
  })
}
// 表单提交
const submitHandle = () => {
  console.log(tableIndex.value);
  if (tableIndex.value == 3) {
    dataFormRef.value.validate((valid: boolean) => {
      if (!valid) {
        return false;
      }

      useTableSubmitApi(dataForm).then(() => {
        ElMessage.success({
          message: "操作成功",
          duration: 500,
          onClose: () => {
            visible.value = false;
            emit("refreshDataList");
          }
        });
      });
    });
  } else {
    useTableFieldSubmitApi(tableId.value, fieldList.value).then(() => {
      ElMessage.success({
        message: "操作成功",
        duration: 500,
        onClose: () => {
          visible.value = false;
          emit("refreshDataList");
        }
      });
    });
  }
};

const dataRules = ref({
  tableName: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
  tableComment: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
  className: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
  packageName: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
  author: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
  moduleName: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
  functionName: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
  generatorType: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
  formLayout: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
  backendPath: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
  frontendPath: [{ required: true, message: "必填项不能为空", trigger: "blur" }]
});

const addSubTable = ()=>{
  if(!dataForm.subTableList){
    dataForm.subTableList = []
  }
  dataForm.subTableList.push({mainTableId:dataForm.id,subTableId:'',mianTableFkName:'',subTableFkName:''})
}

defineExpose({
  init
});
</script>

<style lang="scss">
.sortable-row-gen .drag-btn {
  cursor: move;
  font-size: 12px;
}

.sortable-row-gen .vxe-body--row.sortable-ghost,
.sortable-row-gen .vxe-body--row.sortable-chosen {
  background-color: #dfecfb;
}
</style>
